//引入express
var express = require('express')
var fs = require('fs')
var path = require('path')
var jwt=require('jsonwebtoken')
var userRouter = express.Router()

//分页查询
userRouter.get('/list', (req, res) => {
    console.log('收到了来自客户端的请求');
    var { page, count } = req.query
    var filepath = path.join('__dirname', '../json/user.json')
    var arr = fs.readFileSync(filepath)
    arr = arr.toString() ? JSON.parse(arr) : []
    var newarr = arr.slice((page - 1) * count, page * count)
    res.send({ code: 200, msg: '请求很成功', list: newarr })
})


//登录接口
userRouter.post('/login', (req, res) => {
    var { ucode, pass } = req.body
    var filepath = path.join('__dirname', '../json/user.json')
    var arr = fs.readFileSync(filepath)
    arr = arr.toString() ? JSON.parse(arr) : []
    var i = arr.findIndex((item) => {
        return item.ucode == ucode
    })
    if (i != -1) {
        var token=jwt.sign({ucode},'1234',{algorithm:'HS256',expiresIn:5*60*1000})
        res.send({ code: 200, msg: '登陆成功', userinfo: arr[i], token })
    } else {
        res.send({ code: 400, msg: '登录失败' })
    }
})

userRouter.post('/register', (req, res) => {
    var { ucode } = req.body

    var filepath = path.join('__dirname', '../json/user.json')
    var arr = fs.readFileSync(filepath)
    arr = arr.toString() ? JSON.parse(arr) : []
    var i = arr.findIndex((item) => {
        return item.ucode == ucode
    })
    if (i != -1) {
        res.send({ code: 400, msg: '注册失败' })

    } else {
        arr.push({ ...req.body,pass: 2, isadmin: true, status: true})
        fs.writeFileSync(filepath, JSON.stringify(arr), 'utf8');
        res.send({ code: 200, msg: '注册成功!' })
    }
})

module.exports = userRouter
